package com.stockz.downloader;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import com.stockz.downloader.breadth.BarListBreadthDownload;
import com.stockz.downloader.breadth.BarListBreadthDownloadPersistenceCallback;
import com.stockz.downloader.breadth.bse.BseBarListBredthDownloader;
import com.stockz.downloader.util.DownloaderConstant;
import com.stockz.equity.manager.ConfigurationManager;
import com.stockz.equity.model.Configuration;
import com.stockz.equity.util.CoreConstant;

@Component
public class DownloadManager implements ApplicationContextAware{
	
	private static Logger logger = Logger.getLogger(DownloadManager.class);
	
	private boolean isLocked;
	private ApplicationContext applicationContext;
	
	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
	
	@Autowired 
	private ConfigurationManager configurationManager;
	@SuppressWarnings("rawtypes")
	@Autowired
	private BseBarListBredthDownloader bseBarListBredthDownloader;
	@Autowired
	private BarListBreadthDownloadPersistenceCallback barListBreadthDownloadPersistenceCallback;
	
	
	@SuppressWarnings("deprecation")
	public Date getLastDownloadDate(){
		logger.trace("getLastDownloadDate called");
		Date lastDownloadDate = new Date(2009-1900,0,1);
		Configuration configuration = configurationManager.getByKey(
				DownloaderConstant.LAST_BSE_BREDTH_DOWNLOAD_DATE);
		if(configuration != null && StringUtils.hasText(configuration.getValue())){
			try{
				lastDownloadDate = CoreConstant.dateFormat.parse(configuration.getValue());
			}catch(ParseException e){
				logger.error("Error while parsing last download date received from database", e);
			}
		}
		logger.trace("Last download date : "+lastDownloadDate);
		return lastDownloadDate;
	}

	@Scheduled(fixedDelay=60000)
	@SuppressWarnings("rawtypes")
	public void download(){
		if(isLocked){
			return;
		}else{
			isLocked = true;
		}

		try{
			Date lastDownloadDate = getLastDownloadDate();
			Date today = CoreConstant.dateFormat.parse(
					CoreConstant.dateFormat.format(new Date()));
			logger.trace("Today : "+today);
			if(lastDownloadDate.after(today)
					|| lastDownloadDate.equals(today)
					|| !isInternetConnectionAvailable()){
				logger.trace("Returning as last download date is either today or future date");
				return;
			}
			
			BarListBreadthDownload barListBreadthDownload = new BarListBreadthDownload();
			barListBreadthDownload.setStartDate(lastDownloadDate);
			barListBreadthDownload.setEndDate(today);
			List callbackList = new ArrayList();
			callbackList.add(barListBreadthDownloadPersistenceCallback);
			bseBarListBredthDownloader.download(barListBreadthDownload, callbackList);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			isLocked = false;
		}
	}
	
	private boolean isInternetConnectionAvailable(){
		return true;
	}
	
}
